package top.happylaishop.shop.controller.fontend;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.happylaishop.shop.dto.ProductDetailDto;
import top.happylaishop.shop.dto.ProductListDto;
import top.happylaishop.shop.service.ProductService;
import top.happylaishop.shop.utils.PageDto;
import top.happylaishop.shop.utils.resp.RestResponse;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/defaultImg")
    public RestResponse<String> getDefaultImg(){
        return RestResponse.defaultSucessData("");
    }

    @RequestMapping("/detail/{id}")
    public RestResponse<ProductDetailDto> getProductDetail(@PathVariable Integer productId){
        return RestResponse.defaultSucessData(productService.getDetailById(productId));
    }

    @GetMapping("/keyword/{keyword}/{pageNum}/{pageSize}/{orderBy}")
    public RestResponse<Page<ProductListDto>> listPage(@PathVariable String keyword,
                       @PathVariable Integer pageNum, @PathVariable Integer pageSize, @PathVariable String orderBy){
        return listPage(keyword, null, pageNum, pageSize, orderBy);
    }

    @GetMapping("/category/{categoryId}/{pageNum}/{pageSize}/{orderBy}")
    public RestResponse<Page<ProductListDto>> listPage(@PathVariable Integer categoryId,
                               @PathVariable Integer pageNum, @PathVariable Integer pageSize, @PathVariable String orderBy){
        return listPage(null, categoryId, pageNum, pageSize, orderBy);
    }

    public RestResponse listPage(String keyword, Integer categoryId, Integer pageNum, Integer pageSize, String orderBy){
        PageDto<ProductListDto> productListDtoPageDto = new PageDto<>();
        productListDtoPageDto.setPage(pageNum == null ? 1 : pageNum);
        productListDtoPageDto.setSize(pageSize == null ? 1 : pageSize);
        if(StrUtil.isBlank(orderBy)){
            orderBy = "price_asc";
        }
        productListDtoPageDto.setOrderBy(orderBy);
        productService.listPage(productListDtoPageDto, categoryId, null);
        return RestResponse.defaultSucessData(productListDtoPageDto);
    }
}
